using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SaveManager : Singleton<SaveManager>
{
    string sceneName = string.Empty;
    public string SceneName { get { return PlayerPrefs.GetString(sceneName); } }
    protected override void Awake()
    {
        base.Awake();
        DontDestroyOnLoad(this);
    }
    private void Update()
    {
        // 按下退出键返回主菜单
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            SceneController.Instance.TransitionToMain();
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            SavePlayerData();
        }
        if (Input.GetKeyDown(KeyCode.L))
        {
            LoadPlayerData();
        }
    }
    public void SavePlayerData()
    {
        if (GameManager.Instance.playerStat != null)
        {
            var data = GameManager.Instance.playerStat.characterData;
            if (data != null)
            {
                Save(data, data.name);
            }
        }
    }
    public void LoadPlayerData()
    {
        if (GameManager.Instance.playerStat != null)
        {
            var data = GameManager.Instance.playerStat.characterData;
            if (data != null)
            {
                Load(data, data.name);
            }
        }
    }
    public void Save(Object obj, string key)
    {
        var jsonData = JsonUtility.ToJson(obj, true);
        PlayerPrefs.SetString(key, jsonData);
        // 同时保存当前场景名
        PlayerPrefs.SetString(sceneName, SceneManager.GetActiveScene().name);
        PlayerPrefs.Save();
    }
    public void Load(Object data, string key)
    {
        if (PlayerPrefs.HasKey(key))
        {
            var jsonData = PlayerPrefs.GetString(key);

            JsonUtility.FromJsonOverwrite(jsonData, data);
        }
    }
}
